const log4js = require('log4js');


// log4js默认的日志级别如下：
// ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < MARK < OFF

const MyLog = function (options) {
    return async (ctx, next) => {
        const start = Date.now();
        log4js.configure({
            appenders: {
                infoLogs: {
                    type: 'file',
                    filename: 'logs/info/file.log',
                    maxLogSize: 10485760, // 10mb,日志文件大小,超过该size则自动创建新的日志文件
                    backups: 5,  // 仅保留最新的5个日志文件
                    compress: true    //  超过maxLogSize,压缩代码
                },
                errorLogs: {
                    type: 'file',
                    filename: 'logs/error/file.log',
                    maxLogSize: 10485760,
                    backups: 20,
                    compress: true
                },
                justErrors: {
                    type: 'logLevelFilter', // 过滤指定level的文件
                    appender: 'errorLogs',  // appender
                    level: 'error'  // 过滤得到error以上的日志
                },
                console: {type: 'console'}
            },
            categories: {
                default: { appenders: ['console', 'justErrors', 'infoLogs'], level: 'info' },
                err: { appenders: ['errorLogs'], level: 'error' },
            }
        });
        const infoLogger = log4js.getLogger('infoLogs');
        const errLogger = log4js.getLogger('errorLogs');
        await next();
        const end = Date.now();
        const responseTime = end - start;
        infoLogger.info(`响应时间为${responseTime / 1000}s`);
    }
};

module.exports = MyLog;
